/**  
 * All rights Reserved, Designed By Android_Robot   
 * @Title:  SupervisionAuthorityActivity.java   
 * @Package com.jiyi.activity.supervision   
 * @Description:    TODO(用一句话描述该文件做什么)   
 * @author: HYM     
 * @date:   2017-10-20 上午9:55:17   
 * @version V1.0     
 */
package com.jiyi.activity.supervision;

import android.app.Dialog;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.jiyi.adapter.CommonAdapter;
import com.jiyi.adapter.ViewHolder;
import com.jiyi.bean.supervision.SupervisionAuthorityEditBean;
import com.jiyi.bean.supervision.SupervisionAuthorityEditBean.RoleList;
import com.jiyi.common.StringInterface;
import com.jiyi.common.VolleyRequest;
import com.jiyi.easemob.util.UserHelp;
import com.jiyi.event.SupervisionAuthorityEvent;
import com.jiyi.inteface.WebApi;
import com.swift.base.ActivityBase;
import com.swift.maintenance.R;
import com.swift.maintenance.base.AppBase;
import com.swift.maintenance.base.AppConfig;
import com.swift.maintenance.utils.ToastUtil;
import com.swift.maintenance.utils.UserInfoUtil;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * @ClassName: SupervisionAuthorityActivity
 * @Description:TODO(监管端权限设置)
 * @author: HYM
 * @date: 2017-10-20 上午9:55:17
 * 
 */
public class SupervisionAuthorityActivity extends ActivityBase {

	/* 头部 */
	@BindView(R.id.tvBack)
	TextView tvBack;
	@BindView(R.id.tvTitle)
	TextView tvTitle;
	@BindView(R.id.tvSearch)
	TextView tvSearch;

	@BindView(R.id.tvName)
	TextView tvName;
	@BindView(R.id.tvUnit)
	TextView tvUnit;
	@BindView(R.id.tvLevel)
	TextView tvLevel;
	@BindView(R.id.tvTel)
	TextView tvTel;
	@BindView(R.id.tvInfo)
	TextView tvInfo;

	@BindView(R.id.spLevel)
	Spinner spLevel;
	@BindView(R.id.etTel)
	EditText etTel;
	@BindView(R.id.etInfo)
	EditText etInfo;

	private String user_id;
	SupervisionAuthorityEditBean mSupervisionAuthorityEditBean;

	Dialog dialog;
	// 页面模式 1 查看 2编辑
	private int model = 1;

	// 角色适配器
	CommonAdapter<RoleList> adapter;
	// 角色列表数据源
	List<RoleList> dataList = new ArrayList<RoleList>();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_supervision_authority);
		ButterKnife.bind(this);
		init();
	}

	@Override
	protected void onDestroy() {
		hideDialog(dialog);
		super.onDestroy();
	}

	private void init() {
		getIntentData();
		setTop();
		setAdapter();
		getData();
	}

	private void setAdapter() {
		adapter = new CommonAdapter<RoleList>(this, dataList,
				R.layout.item_state_small) {

			@Override
			public void convert(ViewHolder holder, RoleList t) {
				holder.setText(R.id.state_name, t.getPosition());
			}
		};
		spLevel.setAdapter(adapter);
	}

	private void getIntentData() {
		user_id = getIntent().getStringExtra("user_id");
	}

	private void getData() {
		Map<String, String> params = new HashMap<String, String>();
		params.put(AppConfig.ACCESS_TOKEN,
				UserInfoUtil.getCurrentUserAccessToken());
		params.put("user_id", user_id);
		params.put("jg_role_id", UserInfoUtil.getCurrentUserSupervisionRole()
				+ "");
		dialog = showDialog(dialog);
		VolleyRequest.StringRequestPost(this,
				WebApi.SUPERVISION_AUTHORITY_SETTING, "", params,
				new StringInterface(this) {

					@Override
					public void stringSuccess(String result) {
						try {
							JSONObject obj = new JSONObject(result);
							String status = obj.getString("status");
							String info = obj.getString("info");
							if (status.equals("200")) {
								String data = obj.getString("data");
								mSupervisionAuthorityEditBean = new Gson()
										.fromJson(
												data,
												SupervisionAuthorityEditBean.class);
								if (mSupervisionAuthorityEditBean == null) {
									ToastUtil.getInstances().showMsg(
											"没有改对象，请重试！");
									finish();
									return;
								}
								tvName.setText(mSupervisionAuthorityEditBean
										.getUser_name());
								tvUnit.setText(mSupervisionAuthorityEditBean
										.getSupervised_name());
								tvLevel.setText(mSupervisionAuthorityEditBean
										.getPosition());
								tvTel.setText(mSupervisionAuthorityEditBean
										.getMobile());
								tvInfo.setText(mSupervisionAuthorityEditBean
										.getComments());
								dataList.addAll(mSupervisionAuthorityEditBean.getRoleList());
								adapter.notifyDataSetChanged();
							} else if (status.equals("404")
									&& info.contains("尚未登录")) {
								ToastUtil.getInstances().showMsg(
										"尚未登录或该用户在其他地方登录，请重新登录！");
								// 清除环信登录
								UserHelp.getInstance().clearUser(
										AppBase.Context, true);
								return;
							} else {
								ToastUtil.getInstances().showMsg(info);
							}
						} catch (JSONException e) {
							e.printStackTrace();
						} finally {
							hideDialog(dialog);
						}
					}

					@Override
					public void stringError(VolleyError error) {
						hideDialog(dialog);
						ToastUtil.getInstances().showMsg(
								R.string.err_http_response);
					}
				});
	}

	private void setTop() {
		tvTitle.setText("权限");
		if (UserInfoUtil.getCurrentUserSupervisionRole() == 1) {
			tvSearch.setCompoundDrawables(null, null, null, null);
			tvSearch.setText("编辑");
		}
		else {
			tvSearch.setVisibility(View.GONE);
		}
	}

	@OnClick({ R.id.tvBack, R.id.tvSearch })
	public void onClick(View view) {
		switch (view.getId()) {
		case R.id.tvBack:
			finish();
			break;
		case R.id.tvSearch:
			if (model == 1) {
				model = 2;
				tvSearch.setText("保存");
				tvLevel.setVisibility(View.GONE);
				tvTel.setVisibility(View.GONE);
				tvInfo.setVisibility(View.GONE);
				etTel.setVisibility(View.VISIBLE);
				etInfo.setVisibility(View.VISIBLE);
				spLevel.setVisibility(View.VISIBLE);
				etTel.setText(tvTel.getText().toString());
				etInfo.setText(tvInfo.getText().toString());
				spLevel.setSelection(getPositionByRoleList(mSupervisionAuthorityEditBean
						.getRoleList()));
			} else {
				doPost();
			}
			break;
		default:
			break;
		}
	}

	private void doPost() {
		final String id = new Gson().fromJson(
				spLevel.getSelectedItem().toString(),
				RoleList.class).getId();
		Map<String, String> params = new HashMap<String, String>();
		params.put(AppConfig.ACCESS_TOKEN,
				UserInfoUtil.getCurrentUserAccessToken());
		params.put("user_id", user_id);
		params.put("comments", etInfo.getText().toString());
		params.put("mobile", etTel.getText().toString());
		params.put("id", id);
		dialog = showDialog(dialog);
		VolleyRequest.StringRequestPost(this,
				WebApi.SUPERVISION_AUTHORITY_SETTING_SAVE, "", params,
				new StringInterface(this) {

					@Override
					public void stringSuccess(String result) {
						try {
							JSONObject obj = new JSONObject(result);
							String status = obj.getString("status");
							String info = obj.getString("info");
							if (status.equals("200")) {
								ToastUtil.getInstances().showMsg(info);
								if (id.equals("2")) {
									EventBus.getDefault().post(new SupervisionAuthorityEvent(user_id));
								}
							} else if (status.equals("404")
									&& info.contains("尚未登录")) {
								ToastUtil.getInstances().showMsg(
										"尚未登录或该用户在其他地方登录，请重新登录！");
								// 清除环信登录
								UserHelp.getInstance().clearUser(
										AppBase.Context, true);
								return;
							} else {
								ToastUtil.getInstances().showMsg(info);
							}
						} catch (JSONException e) {
							e.printStackTrace();
						} finally {
							hideDialog(dialog);
						}
					}

					@Override
					public void stringError(VolleyError error) {
						hideDialog(dialog);
						ToastUtil.getInstances().showMsg(
								R.string.err_http_response);
					}
				});
	}

	int getPositionByRoleList(List<RoleList> tempList) {
		for (int i = 0; i < tempList.size(); i++) {
			if (mSupervisionAuthorityEditBean.getPosition().equals(
					tempList.get(i).getPosition())) {
				return i;
			}
		}
		return 0;
	}
}
